<?php
class Core_Authentication_Acl extends Zend_Acl {
	protected $_noauth;
	protected $_noacl;
	
	/***
	 * properties
	 */
	
	public function setNoAuth($noauth) {
		$this->_noauth = $noauth;
	}
	public function getNoAuth() {
		return $this->_noauth;
	}
	public function setNoAcl($noacl) {
		$this->_noacl = $noacl;
	}
	public function getNoAcl() {
		return $this->_noacl;
	}
	
	public function __construct(){
		$rulesCollection = Core_Business_Rule::getRules();
		$this->_addRules($rulesCollection);
		//$this->_loadRedirectionAction($rulesCollection);
		$this->init();
	}
	
	protected function init() {
		
		$auth = Zend_Auth::getInstance();
		/*if($auth->getIdentity()!==null) {
			$user = $auth->getIdentity();
			$rule = Core_Business_Rule::getRuleByName($user->getRole());
		}
		else {
			$rule =Core_Business_Rule::getRuleById(1);
		}*/
		
		/***
		 * add guest user and the appropriated Acl
		 */
		$resources = Core_Authentication_Business_Resource::getAll();
		foreach ($resources as $resource) {
			$this->addResource(new Core_Authentication_Resource($resource->Controller));
			/*$aclForResource = Core_Authentication_Business_Resourceprivilege::getAclByResourceIdRuleId($resource->Id, $rule->Id);
			foreach ($aclForResource as $acl) {
				$rule = $acl->Rule;
				//$resource = $acl->Resource;
				$privilege = $acl->Privilege;
				if($acl->Allow) {
					$this->allow($rule->Name,$resource->Controller,$privilege->Name);
				}
				else {
					$this->deny($rule->Name,$resource->Controller,$privilege->Name);
				}
			}*/
		}
		
		/***
		 * load acl rules
		 */
		$aclcollection = Core_Authentication_Business_Resourceprivilege::getAllAcl();
		
		foreach ($aclcollection as $acl) {
			$rule = $acl->Rule;
			$resource = $acl->Resource;
			$privilege = $acl->Privilege;
			if($acl->Allow) {
				$this->allow($rule->Name,$resource->Controller,$privilege->Name);
			}
			else{ 
				$this->deny($rule->Name,$resource->Controller,$privilege->Name);
			}
		}
		
		
		//$this->allow("guest","Search","Searched");
	}
	
	protected function _addRules($roles) {
		$roles = $roles==null ? array():$roles;
		foreach ($roles as $role) {
			if(!$this->hasRole($role->Name)) {
				//if(empty($parents)) {
					$parents = null;
				/*}
				else {
					$parents = explode(',', $parents);
				}*/
				$this->addRole(new Zend_Acl_Role($role->Name),$parents);
			}
		}
	}
	
	protected  function _loadRedirectionAction($aclConfig) {
		$this->_noauth = array('controller'=>'auth','module'=>'default','action'=>'login');
		$this->_noacl =  array('controller'=>'auth','module'=>'default','action'=>'login');
	}
}